package com.quectel.util.common;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import com.quectel.util.ex.common.OperateFileException;
import com.quectel.util.http.HttpRestUtils;
import com.quectel.util.security.UUIDUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * 文件帮助类 由于很多第三方实现都是FileUtils所以自定义的加上My
 */
public class MyFileUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyFileUtils.class);

    private static final HttpRestUtils HTTP_REST_UTILS = HttpRestUtils.getTrustSSLInstance();


    /**
     * @param in             流对象
     * @param fileName       文件名
     * @param keepOriginName 是否保持原文件名 建议不保持防止重复
     * @return 使用完建议删除
     */
    public static File writeFileToTempDir(InputStream in, String fileName, boolean keepOriginName) {
        if (!keepOriginName) {
            String extName = FileUtil.extName(fileName);
            if (StringUtils.isBlank(extName)) {
                fileName = UUIDUtils.gen32UUID() + ".file";
            } else {
                fileName = UUIDUtils.gen32UUID() + "." + extName;
            }
        }
        File tempFile = new File(FileUtil.getTmpDir(), fileName);
        try (InputStream inputStream = in; OutputStream outputStream = new FileOutputStream(tempFile)) {
            IOUtils.copyLarge(inputStream, outputStream);
        } catch (Exception e) {
            throw new OperateFileException("File copy exception", e);
        }

        return tempFile;
    }


    /**
     * 根据下载文件至操作系统临时目录 并返回文件对象
     *
     * @param url                  网络url
     * @param keepOriginalFileName true代表保持原文件名  false默认采用uuid+文件后缀 建议false
     * @return 返回生成的文件建议删除
     */
    public static File downloadToTempDir(String url, boolean keepOriginalFileName) {
        return downloadToTempDirWithBasicAuth(url, keepOriginalFileName, null, null);
    }

    /**
     * 根据下载文件至操作系统临时目录 并返回文件对象(Basic认证模式)
     *
     * @param url                  网络url
     * @param keepOriginalFileName true代表保持原文件名  false默认采用uuid+文件后缀 建议false
     * @param username             Basic认证账号
     * @param password             Basic认证密码
     * @return 返回生成的文件建议删除
     */
    public static File downloadToTempDirWithBasicAuth(String url, boolean keepOriginalFileName, String username, String password) {
        LOGGER.debug("Start download,url is:{},and {} keep original file name", url, keepOriginalFileName ? "need" : "not need");

        String fileName = getFileNameFromUrl(url);

        if (!keepOriginalFileName) {
            String fileExt = FileUtil.extName(fileName);
            fileName = UUIDUtils.gen32UUID() + (StringUtils.isNotBlank(fileExt) ? ("." + fileExt) : "");
        }
        HttpResponse httpResponse = null;
        try {
            HttpGet httpGet = new HttpGet(url);
            if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
                httpGet.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + Base64.encode(username.concat(":").concat(password), StandardCharsets.UTF_8));
            }
            httpResponse = HTTP_REST_UTILS.getHttpClient().execute(httpGet);

            File tempFile = writeFileToTempDir(httpResponse.getEntity().getContent(), fileName, keepOriginalFileName);
            LOGGER.debug("Download file to tmp dir success,the absolute path is:{},file size {} bytes", tempFile.getAbsolutePath(), tempFile.length());
            return tempFile;
        } catch (IOException e) {
            throw new OperateFileException("Download file failed", e);
        } finally {
            if (httpResponse instanceof CloseableHttpResponse) {
                try {
                    ((CloseableHttpResponse) httpResponse).close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static String getFileNameFromUrl(String url) {
        try {
            if (url == null) {
                return null;
            }
            if (url.contains("?")) {
                return url.substring(url.lastIndexOf("/") + 1, url.indexOf("?"));
            }
            return url.substring(url.lastIndexOf("/") + 1);
        } catch (Exception e) {
            LOGGER.error("Parse url error", e);
        }
        return "";
    }


    public static void main(String[] args) throws IOException {
//        Img.from(new File("/Users/cl/Downloads/591be1924f144cd69ad7c5104ef2ef05.jpeg")).scale(0.2f).write(new File("/Users/cl/Downloads/a.jpeg"));
//        File file = compressImgWriteToTempDir(new FileInputStream("/Users/cl/Downloads/64f459fae700477f8e0ef251ddcbfb96.jpeg"), "a.jpeg", false);
//        System.out.println(file.getAbsolutePath());

    }

}
